<template>
  <div class="create-order">
    <h2>创建订单</h2>
    <el-form @submit.prevent="handleCreateOrder" :model="formData" :rules="rules" ref="orderForm">
      <el-form-item label="预下单号" prop="preOrderNo">
        <el-input v-model="formData.preOrderNo" placeholder="请输入预下单号"></el-input>
      </el-form-item>

      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="formData.payType">
          <el-option label="PayPal" value="paypal"></el-option>
          <el-option label="信用卡" value="creditcard"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="支付渠道" prop="payChannel">
        <el-select v-model="formData.payChannel">
          <el-option label="PayPal PC" value="paypalpc"></el-option>
          <el-option label="信用卡 PC" value="creditcardpc"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="formData.mark" placeholder="备注（可选）"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading">提交订单</el-button>
      </el-form-item>
    </el-form>

    <el-alert v-if="error" :title="error" type="error" show-icon></el-alert>
    <el-alert v-if="orderInfo && orderInfo.orderNo" :title="`订单创建成功，订单号：${orderInfo.orderNo}`" type="success" show-icon></el-alert>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const store = useStore();

const formData = reactive({
  preOrderNo: '',
  payType: 'paypal',
  payChannel: 'paypalpc',
  mark: 'test'
});

const loading = ref(false);
const error = ref('');
const orderForm = ref(null);

const orderInfo = computed(() => store.getters['createOrder/getOrderInfo'] || {});

const rules = {
  preOrderNo: [{ required: true, message: '请输入预下单号', trigger: 'blur' }],
  payType: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  payChannel: [{ required: true, message: '请选择支付渠道', trigger: 'change' }],
};

const handleCreateOrder = async () => {
  try {
    await orderForm.value.validate();
    loading.value = true;
    error.value = '';

    const result = await store.dispatch('createOrder/createOrder', formData);

    if (result.success) {
      ElMessage.success('订单创建成功');
    } else {
      error.value = result.error || '订单创建失败';
    }
  } catch (err) {
    console.error('订单创建失败:', err);
    error.value = '订单创建失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.create-order {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.el-form {
  margin-top: 20px;
}
</style>
